package org.example.springblogg.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.example.springblogg.constant.Constants;
import org.example.springblogg.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws  Exception{
        //1.获取token

        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        log.info("从Header中获取到token：{}",token);


        //2. 校验token，判断是否放行
        Claims claims = JwtUtils.parseToken(token);
        if(claims == null){
            //校验失败：
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
